<?php
//------------------------
// 商品评论控制器
//-------------------------

namespace app\home\controller;

use app\common\controller\HomeBase;
use think\Session;
use app\common\model\GoodsComment as GoodsCommentModel;
use app\common\model\GoodsImpression as GoodsImpressionModel;
use think\Cookie;


class GoodsComment extends HomeBase
{
    protected $GoodsCommentModel;
	protected $GoodsImpressionModel;

	protected function _initialize()
    {
        parent::_initialize();
        $this->GoodsCommentModel              = new GoodsCommentModel();
        $this->GoodsImpressionModel                = new GoodsImpressionModel();
    }



    public function CommentHandle(){
        $data = $this->request->param('');
        $impression = $this->request->param('impression','','trim');

        if (!session('user_id')) {
            $this->error('请登陆后再作评论');
        }

        $validate_result = $this->validate($data, 'GoodsComment.comment');

        if ($validate_result !== true) {
                $this->error($validate_result);
        }

        $commentData = array(
            'user_id'      => session('user_id'),
            'goods_id'     => $data['goods_id'],
            'content'      => $data['content'],
            'comment_rank' => $data['comment_rank'],
            'created_time' => time(),
        );


        if($impression){
            // 先统计字符串中的，号都用英文的
            $impression = str_replace('，', ',', $impression);
            // 先把印象根据，号转化成数组
            $impression = explode(',', $impression);

            $impAddData = array();
            $i          = 0;

            foreach ($impression as $k => $v){
                // 判断这个商品有没有这个印象
                $imp_id = $this->GoodsImpressionModel
                            ->field('id')
                            ->where('goods_id',$data['goods_id'])
                            ->where('imp_name',$v)
                            ->find();

                // 这件商品已经有这个印象就把印象的数字加1
                if($imp_id){
                    $this->GoodsImpressionModel->where('id',$imp_id['id'])->setInc('imp_count');
                } else {
                    $impAddData[$i] = array(
                        'goods_id'  => $data['goods_id'],
                        'imp_name'  => $v,
                        'imp_count' => 1,
                    );

                    $validate_result2 = $this->validate($impAddData[$i], 'GoodsImpression');

                    if ($validate_result2 !== true) {
                            $this->error($validate_result2);
                    }

                    $i = ++$i;
                }
            }

            $this->GoodsImpressionModel->saveAll($impAddData);
        }

        $res = $this->GoodsCommentModel->save($commentData);

        if ($res === false) {
            $this->error($this->GoodsCommentModel->getError());
        } else {
            $this->success('评论提交成功，等待审核中！');
        }

    }


}
